from optparse import OptionParser
import traceback
import json

def extract_error_log(log_file="bg.log"):
    """提取日志中的报错信息"""
    try:
        with open(log_file, encoding="utf-8") as fo:
            with open("error.log", "w", encoding="utf-8") as err:
                for line in filter(lambda line: line.startswith("OnErr"), fo.readlines()):
                    err.write(line)
    except:
        print(traceback.format_exc())


def extract_trade_log(log_file="bg.log"):
    """提取日志中的交易信息"""
    try:
        with open(log_file, encoding="utf-8") as fo:
            with open("trade.log", "w", encoding="utf-8") as log:
            #     for line in filter(lambda line: line.startswith("OnRtnTrade") or line.startswith("CloseProfit"), fo.readlines()):
            #         if line.startswith("OnRtnTrade"):
            #             jsonstr = line.lstrip("OnRtnTrade, data=").split("}")[0] + "}"
            #             try:
            #                 pTrade = json.loads(jsonstr)
            #             except:
            #                 print(traceback.format_exc())
            #                 print(jsonstr)
            #             trade.write("[OnRtnTrade][%s] %6.3f %3d  %s  %s\n" % (pTrade["InstrumentID"], pTrade["Price"], pTrade["Volume"], \
            #                 "Buy " if pTrade["Direction"] == "0" else "Sell", \
            #                 "Open " if pTrade["OffsetFlag"] == "0" else "Close"))
            #         else:
            #             trade.write(line)
                trades = []
                for line in filter(lambda line: line.startswith("OnRtnTrade"), fo.readlines()):
                    jsonstr = line.lstrip("OnRtnTrade, data=").split("}")[0] + "}"
                    pTrade = json.loads(jsonstr)
                    trades.append(pTrade)
                for pTrade in sorted(trades, key=lambda t:t["OrderSysID"]):
                    log.write("[OnRtnTrade][%s] %6d %6.3f %3d  %s  %s\n" % \
                        (pTrade["InstrumentID"], pTrade["OrderSysID"], pTrade["Price"], pTrade["Volume"], \
                        "Buy " if pTrade["Direction"] == "0" else "Sell", \
                        "Open " if pTrade["OffsetFlag"] == "0" else "Close"))
    except:
        print(traceback.format_exc())


if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option("-i", "--index", dest="index", help="log index")
    (options, args) = parser.parse_args()

    log_file = "bg.log"
    if options.index:
        log_file = "bg_%s.log" % options.index
    
    # extract_error_log(log_file)
    extract_trade_log(log_file)
